package spring.data.jpa.config;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.config.ConfigurationUtils;
import org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
import org.w3c.dom.Element;

public class SimpleXmlRepositoryBeanDefinitionParser implements BeanDefinitionParser {

    public BeanDefinition parse(Element element, ParserContext parser) {
        BeanDefinitionRegistry registry = parser.getRegistry();
        RepositoryConfigurationExtension extension = new JpaRepositoryConfigExtension();
        XmlReaderContext readerContext = parser.getReaderContext();
        ResourceLoader resourceLoader = ConfigurationUtils.getRequiredResourceLoader(readerContext);
        Environment environment = readerContext.getEnvironment();
        SimpleXmlRepositoryConfigurationSource configurationSource = new SimpleXmlRepositoryConfigurationSource(
                element, parser, environment);
        SimpleRepositoryConfigurationDelegate delegate = new SimpleRepositoryConfigurationDelegate(configurationSource,
                resourceLoader, environment);
        for (BeanComponentDefinition definition : delegate.registerRepositoriesIn(registry, extension)) {
            readerContext.fireComponentRegistered(definition);
        }
        return null;
    }

}
